import 'dart:convert';

import 'package:flutter_chubao/binging/app_getx_user.dart';
import 'package:flutter_chubao/models/model_user.dart';
import 'package:flutter_chubao/pages/main/app_main/app_main_logic.dart';
import 'package:flutter_chubao/tools/shared/app_shared.dart';
import 'package:flutter_chubao/tools/tool_app/app_dio_client.dart';
import 'package:flutter_chubao/tools/tool_app/app_dio_response.dart';
import 'package:get/get.dart';

class AppManagerUser {
  static Future initStorage() async {
    UserEntity userSaveEntity = await AppSharedStorage.getUserInfoLocal();
    if ((userSaveEntity.token ?? '').isNotEmpty) {
      var token = AppSharedPro.getString(AppShareConstant.userToken);
      AppDioClient.appToken = token;
      var userdata = AppSharedPro.getString(AppShareConstant.userInfo);
      Map<String, dynamic> userMap =
          userdata.isNotEmpty ? jsonDecode(userdata) : {};
      updataUserInfo(UserEntity.fromJson(userMap));
    }
  }

  static bool isLogin() {
    // DLog(Get.find<AppGetxUser>().userEntity);
    return (Get.find<AppGetxUser>().userEntity.token ?? '').isNotEmpty;
  }

  static Future<UserEntity?> getPostUserInfo() async {
    AppDioResponse response = await AppDioClient.post(
      '/mini/chubao/userinfo',
    );
    if (response.ok) {
      UserEntity userInfoEntity = UserEntity.fromJson(response.data);
      return userInfoEntity;
    }
    return null;
  }

  static Future updataUserInfo(UserEntity userModel) async {
    if ((userModel.token ?? '').isEmpty) {
      userModel.token = AppDioClient.appToken;
    }
    Get.find<AppGetxUser>().updateUser(userModel);
    await AppSharedStorage.saveUserInfo(userModel);
  }

  static Future userLogin(UserEntity userModel) async {
    Get.find<AppGetxUser>().updateUser(userModel);
    await AppSharedStorage.saveUserInfo(userModel);
    await AppSharedPro.setString(
        AppShareConstant.userToken, userModel.token ?? '');
    await AppSharedPro.setString(
        AppShareConstant.userId, (userModel.id ?? '').toString());

    if ((userModel.token ?? '').isNotEmpty) {
      AppDioClient.appToken = userModel.token ?? '';
    }
    Get.find<AppMainLogic>().getTabbarDataSource();
    Get.until((route) {
      return route.isFirst;
    });

    // Get.back();
    Get.find<AppMainLogic>().update();
  }

  static userLoginOut() {
    if (AppManagerUser.isLogin()) {
      AppDioClient.get(
        'user/logout',
      );
      Get.find<AppGetxUser>().removeUserData();
      AppSharedPro.removeOnly(AppShareConstant.userInfo);
      AppSharedPro.removeOnly(AppShareConstant.userToken);
      AppSharedPro.removeOnly(AppShareConstant.userId);
    }
    AppDioClient.appToken = '';
    Get.until((route) {
      return route.isFirst;
    });
    Get.find<AppMainLogic>().update();
    // Get.find<AppMineLogic>().clickPage(0);
    // Get.find<SsHomeLogic>().getHomeData();
  }
}
